package com.atguigu.Flink.timeAndwindow;

import com.atguigu.Flink.POJO.Event;
import com.atguigu.Flink.POJO.WordCount;
import com.atguigu.Flink.function.ClickSource;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Flink08_ProcessWindowFunction {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<Event> ds = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event event, long l) {
                                return event.getTs();
                            }
                        })
                );
        ds.print("input");

        //需求: 统计每10秒内每用户的点击次数， 并且要包含窗口信息
        ds.map(
                event -> new WordCount(event.getUser(),1L)
        ).keyBy(
                key->key.getWord()
        ).window(
                TumblingEventTimeWindows.of(Time.seconds(10))
        ).process(
                new ProcessWindowFunction<WordCount, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WordCount, String, String, TimeWindow>.Context context, Iterable<WordCount> iterable, Collector<String> collector) throws Exception {
                            String user = s;
                            Long count = 0L;
                        for (WordCount wordCount : iterable) {
                            count++;
                        }
                        long start = context.window().getStart();
                        long end = context.window().getEnd();
                        collector.collect("窗口[ " + start + " ~ " + end + " )  , 用户 " + user + " 的点击次数为: " + count);

                    }
                }
        ).print("window");
        

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
